package controller

import (
	"net/http"
	"poker/enum"
	"poker/model"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

func CreateOrder(c *gin.Context) {
	order := model.Order{}
	if err := c.BindJSON(&order); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}

	order2 := model.Order{}
	filter := bson.M{"_id": order.ID, "status": enum.ORDER_STEP1_CREATED}
	if err := order2.FindOne(filter); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}

	if order2.ExtraInfo != order.ExtraInfo {
		c.JSON(http.StatusAccepted, gin.H{"msg": "extra info check error"})
		return
	}

	order2.Status = enum.ORDER_STEP2_SEND
	order2.UpdateDate = time.Now().Format("2006/01/02 15:04:05")

	if err := order2.UpdateOne(bson.M{"_id": order2.ID}); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
	}

	c.JSON(http.StatusOK, order2.ExtraInfo)
}

func GetOrders(c *gin.Context) {
	uid := c.Query("uid")
	if uid == "" {
		c.JSON(http.StatusAccepted, gin.H{"msg": "uid is empty"})
		return
	}
	orders, err := model.GetOrdersByUid(uid)
	if err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, orders)
}

func ReSendOrder(c *gin.Context) {
	uid := c.Query("uid")
	if uid == "" {
		c.JSON(http.StatusAccepted, gin.H{"msg": "uid is empty"})
		return
	}

	order := &model.Order{}
	filter := bson.M{"uid": uid, "status": enum.ORDER_STEP2_SEND}
	if err := order.FindOne(filter); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}

	order.Status = enum.ORDER_STEP1_CREATED
	order.UpdateDate = time.Now().Format("2006/01/02 15:04:05")

	if err := order.UpdateOne(bson.M{"_id": order.ID}); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}

	c.String(http.StatusOK, "ok")
}

func OrderFinish(c *gin.Context) {
	customId := c.Query("customId")
	if customId == "" {
		c.JSON(http.StatusAccepted, gin.H{"msg": "customId is empty"})
		return
	}

	order := &model.Order{}
	filter := bson.M{"_id": customId, "status": enum.ORDER_STEP2_SEND}
	if err := order.FindOne(filter); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}

	order.Status = enum.ORDER_STEP3_FINISH
	order.UpdateDate = time.Now().Format("2006/01/02 15:04:05")

	if err := order.UpdateOne(bson.M{"_id": order.ID}); err != nil {
		c.JSON(http.StatusAccepted, gin.H{"msg": err.Error()})
		return
	}

	c.String(http.StatusOK, "ok")
}

func QueryPayState(c *gin.Context) {

}
